package com.wanjia.estate.service.httpservice;

import cn.com.infosec.netsign.agent.PBCAgent2G;
import cn.com.infosec.netsign.crypto.util.Base64;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;


@Service
@Slf4j
public class NxKeyService {

    /*加签*/
    public String NxAddKey(String request) throws Exception {
        //获取签名服务器
        PBCAgent2G pbc = new PBCAgent2G();
        //行内签名服务器的ip、 端口、密码
        pbc.openSignServer("192.168.2.14", "9011", "11111111");
        //开始对明文进行加签验签 用于报文发送省联社
        //报文原文request
        //报文加签验签，000固定不恋，SM3固定不变，SM4固定不恋
        String result = pbc.makeMSEnvelope(request.getBytes("UTF-8"), "", "000", "SM3", "SM4");
        log.debug("result: {}", result);
        // pbc.getReturnCode()获取操作返回代码,1代表成功
        if (pbc.getReturnCode() != 1) {
            throw new RuntimeException("加签失败");
        }
        // result输出结果
        return result;
    }


    /*验签*/
    public String NxDecryptKey(String response) throws Exception {
        //接收省联社密文进行解密验签response
        //获取签名服务器
        PBCAgent2G pbc = new PBCAgent2G();
        //行内签名服务器的ip、 端口、密码
        pbc.openSignServer("192.168.2.14", "9011", "11111111");
        //参数2填写法人三位法人号，SM3固定不变
        Object[] result = pbc.decryptMSEnvelope(response, "000", "SM3");
        if (pbc.getReturnCode() != 1) {
            throw new RuntimeException("验签失败");
        }
        return new String(Base64.decode(result[0].toString()), StandardCharsets.UTF_8);
    }


}
